import type { GoodsItemModel, GoodsItemskuListModel, GoodsItemskuListVModel } from '@/api/goods'

export interface SpecListItem<T=GoodsItemskuListVModel> {
  list: T[]
  name: string
  skuId?: number
}
// 处理商品的spec_list规格列表
export function setSpec_list(skulist: GoodsItemskuListModel[], type: string): SpecListItem[] {
  const data: SpecListItem[] = []
  switch (type) {
    case 'none':
      data.push({
        list: [{
          name: '默认',
        }] as GoodsItemskuListVModel[],
        name: '默认',
      })
      break
    default:
      skulist.forEach((item) => {
        data.push({
          list: item.v,
          name: item.k,
          skuId: item.id,
        })
      })
      break
  }
  return data
}

export interface SkuListItem {
  _id: number
  goods_id: number
  goods_name: string
  image: string
  sku_name_arr: string[]
  price: string
  stock: number
  indexList: { parentIndex: number; sonIndex: number }[]
}
// 处理商品的Sku_list sku列表
export function setSku_list(goodsItem: GoodsItemModel, type: string): SkuListItem[] {
  const data: SkuListItem[] = []
  switch (type) {
    case 'none': // 无规格
      data.push({
        _id: goodsItem.id,
        goods_id: goodsItem.id,
        goods_name: goodsItem.name,
        image: goodsItem.iconId[0].url,
        sku_name_arr: ['默认'],
        price: goodsItem.price,
        stock: goodsItem.stock_num,
        indexList: [],
      })
      break
    default: // 多规格
      goodsItem.list?.forEach((item) => { // 先循环list数组
        item.indexList = [] // 存储索引位置
        for (const prop in item) { // 再循坏listitem对象(匹配规格列表)
          goodsItem.skuList.forEach((value, idx) => {
            if (prop === value.k_s) { // 当前匹配到规格一级父类
              const index = value.v.findIndex(i => i.id === item[prop])
              item.indexList.push({
                parentIndex: idx, // 父类索引
                sonIndex: index, // 子类索引
              })
            }
          })
        }
        data.push({
          _id: item.id,
          goods_id: goodsItem.id,
          goods_name: goodsItem.name,
          image: '',
          sku_name_arr: [],
          price: item.price,
          stock: item.stock_num,
          indexList: item.indexList,
        })
      })
      // 完成后再补齐sku规格头像和sku名称
      data.forEach((item) => {
        item.indexList.forEach((value) => {
          item.sku_name_arr.push(goodsItem.skuList[value.parentIndex].v[value.sonIndex].name)
          item.image = goodsItem.skuList[value.parentIndex].v[value.sonIndex].previewImgUrl?.[0]?.url || ''
        })
        // 如果没有sku头像则用商品封面代替
        item.image = item.image ? item.image : goodsItem.iconId[0].url
      })
      break
  }
  return data
}
